package com.lagou.homework.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/*
 * @className JDBCUtils
 * @description JDBC工具类-druid
 * @author admin
 * @date 2022/4/11 15:14
 * */
public class JDBCUtils {

    // 1.定义静态成员变量
    public static DataSource dataSource;

    // 2.静态代码块 随着类的加载而加载
    static {
        // 3.创建属性集对象
        Properties p = new Properties();
        // 4.加载配置文件
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            // 5.通过Properties对象调用load方法从字节流中读取配置文件信息
            p.load(is);
            // 6.通过工厂类获取连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 7.从连接池中获取连接
    public static Connection getConnection() throws SQLException {
        Connection con = dataSource.getConnection();
        return con;
    }

    // 8.释放资源
    public static void close(Connection con, Statement statement) {
        if (null != con) {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void close(Connection con, Statement statement, ResultSet rs) {
        if (null != rs) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (null != con) {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
